package com.yh.csx.crm.service;

import com.alibaba.fastjson.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.persistent.FileRecorder;
import com.qiniu.util.Auth;
import com.yh.csx.crm.core.exception.BusinessException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.InputStream;

/**
 * @author Huang Zhaoping
 * @date 2019/1/25
 */
/*
@Service
public class FileService implements InitializingBean {

    @Value("${qiniu.accessKey}")
    private String accessKey;
    @Value("${qiniu.securityKey}")
    private String securityKey;
    @Value("${qiniu.privateBucket}")
    private String privateBucket;
    @Value("${qiniu.privateUrl}")
    private String privateUrl;
    @Value("${qiniu.publicBucket}")
    private String publicBucket;
    @Value("${qiniu.publicUrl}")
    private String publicUrl;

    private Auth auth;
    private UploadManager uploadManager;
    private BucketManager bucketManager;


    @Override
    public void afterPropertiesSet() throws Exception {
        auth = Auth.create(accessKey, securityKey);
        Configuration configuration = new Configuration(Zone.autoZone());
        uploadManager = new UploadManager(configuration, new FileRecorder("tmp/"));
        bucketManager = new BucketManager(auth, configuration);
        if (!publicUrl.endsWith("/")) {
            publicUrl = publicUrl + "/";
        }
        if (!privateUrl.endsWith("/")) {
            privateUrl = privateUrl + "/";
        }
    }

    public String uploadFile(InputStream input, String path, boolean isPrivate) {
        String bucket = isPrivate ? privateBucket : publicBucket;
        String baseUrl = isPrivate ? privateUrl : publicUrl;
        String token = auth.uploadToken(bucket);
        DefaultPutRet putRet;
        try {
            if (path.startsWith("/")) {
                path = path.substring(1);
            }
            Response response = uploadManager.put(input, path, token, null, null);
            if (response.statusCode != 200) {
                throw new Exception("文件上传返回状态异常：" + response.statusCode);
            }
            putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
        } catch (QiniuException e) {
            throw new BusinessException("文件服务异常", e);
        } catch (Exception e) {
            throw new BusinessException("上传文件异常", e);
        }
        if (!baseUrl.endsWith("/")) {
            baseUrl += "/";
        }
        return baseUrl + putRet.key;
    }

    public String authPrivateUrl(String url, int expires) {
        return auth.privateDownloadUrl(url, expires);
    }
}*/
